package com.fx.zmlzml.controller;

import com.fx.zmlzml.common.response.Result;
import com.fx.zmlzml.entity.PcCase;
import com.fx.zmlzml.exception.BusinessException;
import com.fx.zmlzml.exception.ErrorEnum;
import com.fx.zmlzml.service.PcCaseService;
import com.fx.zmlzml.util.MessageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 电脑机箱 Controller
 * 提供RESTful API接口，用于操作电脑机箱数据
 */
@RestController
@RequestMapping("/api/case")
@Tag(name = "电脑机箱管理", description = "提供电脑机箱的CRUD操作及相关查询功能")
public class PcCaseController {
    
    private static final Logger logger = LoggerFactory.getLogger(PcCaseController.class);
    
    @Autowired
    private PcCaseService pcCaseService;
    
    /**
     * 分页查询电脑机箱
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询电脑机箱", description = "分页查询电脑机箱信息，支持页码和每页大小参数")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PageInfo<PcCase>> getPcCasesByPage(
            @Parameter(description = "页码，默认为1", example = "1", required = false) @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数，默认为15", example = "15", required = false) @RequestParam(defaultValue = "15") Integer pageSize) {
        logger.info("分页查询电脑机箱请求，页码：{}，每页大小：{}", pageNum, pageSize);
        try {
            // 参数校验
            if (pageNum < 1 || pageSize < 1) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID,
                        MessageUtils.getMessage("common.validation.page_num") + "，" + 
                        MessageUtils.getMessage("common.validation.page_size"));
            }

            PageHelper.startPage(pageNum, pageSize);
            List<PcCase> list = pcCaseService.list();
            PageInfo<PcCase> pageInfo = new PageInfo<>(list);

            logger.debug("分页查询电脑机箱成功，总数：{}", pageInfo.getTotal());
            return Result.i18nSuccess(pageInfo, "case.query.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("分页查询电脑机箱失败，页码：{}，每页大小：{}", pageNum, pageSize, e);
            return Result.error(MessageUtils.getMessage("query.failed"));
        }
    }
    
    /**
     * 根据ID获取电脑机箱详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取电脑机箱详情", description = "根据唯一标识符查询电脑机箱的详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到资源", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcCase> getPcCaseById(
            @Parameter(description = "电脑机箱ID", example = "1", required = true) @PathVariable Long id) {
        logger.info("查询电脑机箱详情请求，ID：{}", id);
        try {
            // 参数校验
            if (id == null || id <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID,
                        MessageUtils.getMessage("common.validation.id"));
            }
            
            PcCase pcCase = pcCaseService.getById(id);
            if (pcCase == null) {
                logger.warn("未找到电脑机箱，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND,
                        MessageUtils.getMessage("case.not_found"));
            }
            logger.debug("查询电脑机箱详情成功，ID：{}", id);
            return Result.success(pcCase);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("查询电脑机箱详情失败，ID：{}", id, e);
            return Result.error(MessageUtils.getMessage("query.failed"));
        }
    }
    
    /**
     * 添加电脑机箱
     */
    @PostMapping
    @Operation(summary = "添加电脑机箱", description = "添加新的电脑机箱信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "添加成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "添加失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> addPcCase(
            @Parameter(description = "电脑机箱信息") @RequestBody PcCase pcCase) {
        logger.info("添加电脑机箱请求，制造商：{}", pcCase.getManufacturer());
        try {
            pcCase.setCreatedTime(new Date());
            pcCase.setUpdatedTime(new Date());
            boolean result = pcCaseService.save(pcCase);
            if (result) {
                logger.debug("添加电脑机箱成功，ID：{}", pcCase.getId());
                return Result.success(result);
            } else {
                logger.warn("添加电脑机箱失败，制造商：{}", pcCase.getManufacturer());
                return Result.error(MessageUtils.getMessage("save.failed"));
            }
        } catch (Exception e) {
            logger.error("添加电脑机箱失败，制造商：{}", pcCase.getManufacturer(), e);
            return Result.error(MessageUtils.getMessage("save.failed"));
        }
    }
    
    /**
     * 更新电脑机箱
     */
    @PutMapping
    @Operation(summary = "更新电脑机箱", description = "更新电脑机箱信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到资源", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "更新失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> updatePcCase(
            @Parameter(description = "电脑机箱信息") @RequestBody PcCase pcCase) {
        logger.info("更新电脑机箱请求，ID：{}", pcCase.getId());
        try {
            // 检查是否存在
            if (pcCaseService.getById(pcCase.getId()) == null) {
                logger.warn("更新电脑机箱时未找到该机箱，ID：{}", pcCase.getId());
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND);
            }
            pcCase.setUpdatedTime(new Date());
            boolean result = pcCaseService.updateById(pcCase);
            if (result) {
                logger.debug("更新电脑机箱成功，ID：{}", pcCase.getId());
                return Result.success(result);
            } else {
                logger.warn("更新电脑机箱失败，ID：{}", pcCase.getId());
                return Result.error(MessageUtils.getMessage("update.failed"));
            }
        } catch (BusinessException e) {
            logger.warn("更新电脑机箱业务异常：{}", e.getMessage());
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("更新电脑机箱失败，ID：{}", pcCase.getId(), e);
            return Result.error(MessageUtils.getMessage("update.failed"));
        }
    }
    
    /**
     * 删除电脑机箱
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除电脑机箱", description = "根据ID删除电脑机箱")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到资源", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "删除失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> deletePcCase(
            @Parameter(description = "电脑机箱ID") @PathVariable Long id) {
        logger.info("删除电脑机箱请求，ID：{}", id);
        try {
            // 检查是否存在
            if (pcCaseService.getById(id) == null) {
                logger.warn("删除电脑机箱时未找到该机箱，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND);
            }
            boolean result = pcCaseService.removeById(id);
            if (result) {
                logger.debug("删除电脑机箱成功，ID：{}", id);
                return Result.success(result);
            } else {
                logger.warn("删除电脑机箱失败，ID：{}", id);
                return Result.error(MessageUtils.getMessage("delete.failed"));
            }
        } catch (BusinessException e) {
            logger.warn("删除电脑机箱业务异常：{}", e.getMessage());
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("删除电脑机箱失败，ID：{}", id, e);
            return Result.error(MessageUtils.getMessage("delete.failed"));
        }
    }
}